use std::process::id;
use concurrency::Metrics;
use rand::Rng;
use std::{
    thread,
    time::Duration
};

const N: usize = 2;
const M: usize = 4;

fn main() -> anyhow::Result<()> {

    let mut metrics = Metrics::new();

    for i in 0..N {
        task_worker(i, metrics.clone())?;
    }

    for _ in 0..M {
        request_worker(metrics.clone())?;
    }

    loop {
        thread::sleep(Duration::from_secs(2));
        println!("{}", metrics);
    }

    Ok(())
}

fn task_worker(idx: usize, mut metrics: Metrics) -> anyhow::Result<()> {
    thread::spawn(move || {
        let mut rng = rand::thread_rng();
        loop {
            thread::sleep(Duration::from_millis(rng.gen_range(20..150)));
            metrics.inc(format!("call.thread.worker.{}", idx));
            // println!("thread: {}", metrics);
        }
    });

    Ok(())
}
fn request_worker(mut metrics: Metrics) -> anyhow::Result<()> {
    thread::spawn(move || {
        let mut rng = rand::thread_rng();
        loop {
            thread::sleep(Duration::from_millis(rng.gen_range(80..200)));
            let page = rng.gen_range(1..5);
            metrics.inc(format!("req.page.{}", page));
        }
    });

    Ok(())
}